package com.ken.ability.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ken.ability.auth.protocol.security.AuthClientDetails;
import com.ken.ability.auth.service.AuthClientService;
import com.ken.common.cache.annotation.CacheGet;
import com.ken.entity.auth.AuthClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@Primary
public class AuthClientDetailsServiceImpl implements ClientDetailsService {

    @Autowired
    private AuthClientService clientService;

    @Override
    @CacheGet(key = "'auth_clients_' + #clientId")
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        //根据clientid 获得AuthClient对象
        QueryWrapper<AuthClient> wrapper = new QueryWrapper<>();
        wrapper.eq("client_id", clientId);
        AuthClient authClient = clientService.getOne(wrapper);
        //创建Security的客户端对象
        AuthClientDetails authClientDetails = new AuthClientDetails();
        BeanUtils.copyProperties(authClient, authClientDetails);
        log.debug("[Auth-Clients] - 获得客户端应用对象：" + authClient);
        return authClientDetails;
    }
}
